/*
* @desc 增删改查操作
* */
define('cruder', ['jquery', 'tool', 'dialoger'], function($, tool, dialoger) {
    var cruder = {
        //更新
        update : function(options){
            var data = {};
            if(options.target){
                var $form = $(options.target),
                    id = options.idKey || $form.find('[value=all]').attr('name') || 'id',
                    arr = [];
                $form.find('input[name=' + id + '][value!=all]').each(function(){
                    var $this = $(this);
                    if(this.checked) arr.push($this.val());
                });
                //判断有无选中项
                if(arr.length < 1){
                    dialoger.error({msg : '未选中任何项'});
                    return;
                }
                data[id] = arr.join(options.storeSplit || ',');
            }

            //附加值
            options.params = $.extend({}, options.params, data);

            //传输数据
            this.ajaxData(options);

        },

        //确认操作
        confirm : function(func, options){
            var me = this;
            options = options || {};
            dialoger.confirm({
                title: options.title || me.title,
                msg: options.msg || "您确定要执行该操作吗？",
                callback : function(flag){
                    if(flag) func();
                }
            });
        },

        //刷新页面
        refresh : function(options){
            options = options || {};
            //bs表格刷新
            if(options.refresh == 'grid'){
                options.url = undefined;
                this.refreshGrider(options);
                return;
            }
            //树形表格刷新
            else if(options.refresh == 'treegrid'){
                options.url = undefined;
                this.refreshTreeGrid(options);
                return;
            }
            //树刷新
            else if(options.refresh == 'tree'){
                options.url = undefined;
                this.refreshTree(options);
                return;
            }
            //可替换元素刷新
            else if(options.refresh == 'object'){
	            options.url = undefined;
	            this.refreshObject(options);
	            return;
            }

            //整个页面刷新
            options.win = options.win || window;
            if(options.jump == 'refresh' || !options.jump) options.jump = options.win.location.href;

            if(options.delay){
                setTimeout(function () {
                    tool.jumpTo(options.jump, options.win);
                }, options.delay);
            }else tool.jumpTo(options.jump, options.win);
        },

        //刷新数据表格
        refreshGrider : function(options){
            options.target = options.target || this.target;
            //基于bs表格选择模块搜索
            if(options.cat == 'west' || options.cat == 'east'){
                require(['dataselector'], function(dataselector){
                    dataselector.refresh(options);
                });
                return;
            }
            require(['grider'], function(grider){
                grider.refresh(options);
            });
        },

        //刷新树形表格
        refreshTreeGrid : function(options){
            var me = this;
            require(['treegrider'], function(treegrider){
                options.target = options.target || me.target;
                treegrider.refresh(options);
            });
        },

        //刷新树
        refreshTree : function(options){
            var me = this;
            require(['tree'], function(tree){
                options.target = options.target || me.target;
                tree.refresh(options);
            });
        },

        //刷新数据选择
        refreshDataSelector : function(options){
            options.target = options.target || this.target;
            require(['dataselector'], function(dataselector){
                dataselector.refresh(options);
            });
        },

	    //刷新可替换元素
	    refreshObject : function(options){
		    options.handler = options.handler || this.target;
		    var $handler = $(options.handler);
		    if (/img/i.test($handler.get(0).tagName)){
			    $handler.attr('src', $handler.attr('src').replace(/(\&|\?)t\=[\.\w]+/, '') + '?t=' + Math.random());
		    }
	    },

        //页面返回
        back : function(options){
            options = options || {};
            if(typeof options.back == 'string'){
                tool.jumpTo(options.back, options.win);
            }else tool.back(options.win);
        },

        //表单重置
        reset : function(options){
            var $el = $(options.handler),
                $form = $el.parents('form');
            if($form.length > 0){
                $form.get(0).reset();
            }
            options.paramsSearch = null;

            //表格
            if(options.reset == 'grid'){
                require(['grider'], function(grider){
                    grider.reset(options);
                });
            }

            //树形表格
            else if(options.reset == 'treegrid'){

            }

        },

        //检测并提交表单
        ajaxValidForm : function(options){
            var me = this, $form = tool.get$el(options.form);
            require(['validater'], function(validater){
                if(validater.isValid($form.get(0))){
                    me.ajaxForm(options);
                }
            });
        },

        //AJAX提交表单
        ajaxForm : function (options) {
            options = options || {};
            if (undefined == options.form || '' == options.form) options.form = 'form';
            var $form = tool.get$el(options.form);
            options = $.extend(tool.parseOptions($form), options);
            if(!options.url) var url = $form.attr('action') || '';
            options.url = options.url || url;
            options.data = tool.serializeObject($form);
            options.type = options.type || $form.attr('method');
            var complete = options.complete || function(){},
                error = options.error || function(){};
            options.complete = function(res){
                setTimeout(function(){
                    $(":submit", $form).removeClass('disabled').prop('disabled', false);
                }, 3000);
                complete(res);
            };
            options.error = function(res){
                $(":submit", $form).removeClass('disabled').prop('disabled', false);
                error(res);
            };
            $(":submit", $form).addClass('disabled').attr('autocomplete','off').prop('disabled',true);

            //传输数据
            this.ajaxData(options);
        },

        //传输数据
        ajaxData : function(options){
            var me = this,
                success = typeof options.success == 'function' ? options.success : function(){},
                error = typeof options.error == 'function' ? options.error : function(){},
                complete = typeof options.complete == 'function' ? options.complete : function(){};
            options.success = function(response, textStatus, jqXHR){
                //回调返回false则不再执行
                if(success(response, options, textStatus, jqXHR) === false) return;
                options.success = null;
                options.complete = null;
                me.handleResp(response, options, textStatus, jqXHR);
            };
            options.error = function(XMLHttpRequest, textStatus, errorThrown){
                //失败后调用
                if(error(XMLHttpRequest, options, textStatus, errorThrown) === false) return;
                options.error = null;
                options.complete = null;
            };
            options.complete = function(XMLHttpRequest, textStatus, errorThrown){
                complete(XMLHttpRequest, options, textStatus, errorThrown);
                options.complete = null;
            };

            require(['ajaxer'], function(ajaxer){
                ajaxer.ajax(options);
            });
        },

        //处理服务器回应
        handleResp : function(response, options, textStatus, jqXHR){
            options = options || {};
            response = response || {};
            options.win = options.win || window;
            var url = response.url, jumpFlag = true;

            //跳转地址控制
            if((response.status && response.status != 0 && response.status != 'false') || options.force){
                url = url || options.jump;
            }
            if((!url && !response.status) || options.stay) jumpFlag = false

            //消息整合
            if(jumpFlag && !options.gridFresh && !options.treeGridFresh){
                response.msg = response.msg || response.info;
                response.msg = (response.msg ? response.msg + '，' : '') + '页面即将跳转～';
            }

            //弹出提示消息
            if (response.status) {
                dialoger.success({msg : response.msg, title : this.title});
            } else {
                dialoger.error({msg : response.msg, title : this.title});
            }
            if(!jumpFlag) return;

            //如果需要跳转的话，消息的末尾附上即将跳转字样
            options.jump = url;
            options.delay = options.delay || 1000;

            //是否返回
            if(options.backResp){
                this.back(options);
            }
            //默认刷新
            else this.refresh(options);
        },

        //弹出框
        dialog : function(options){
            if(options.add){
                options.title = options.title || '添加';
            }else if(options.edit){
                options.title = options.title || '编辑';
            }
            //本页面弹出指定元素
            if(options.popup) {
                this.popup(options);
            }
            //本页面弹出指定元素窗口
            else if(options.dialog) {
                this.dialogLoad(options);
            }
            //iframe窗口
            else if(options.frame) {
                this.dialogFrame(options);
            }
            //弹出load窗口
            else if(options.load) {
                this.dialogLoad(options);
            }
        },

        //弹出iframe框
        dialogFrame : function(options){
            var me = this;
            options.okHandler = options.okHandler || formController;

            //表单操作
            function formController(){
	            var $this = $(this),
		            $dialog = $this.hasClass('modal-dialoger') ? $this : $this.parents('.modal-dialoger'),
                    contentWindow = $dialog.find('iframe').get(0).contentWindow,
                    submitForm = contentWindow.submitForm, form;
                if(submitForm){
                    contentWindow.submitForm($dialog, window);
                    return;
                }
                form = contentWindow.$('form.submitform');
                if(form.length > 0) {
                    me.ajaxValidForm({
                        form: form,
                        complete: function (response) {
                            if (response.status) {
                                $dialog.modal('hide');
                            }
                        }
                    });
                }else{
                    $dialog.modal('hide');
                }
            }

            dialoger.dialog(options);
        },

        //弹出load框
        dialogLoad : function(options){
            var me = this;
            options.okHandler = options.okHandler || formController;
            var complete = options.completeFunc || function(){}, $dialog;
            //加载的内容需要初始化
            options.completeFunc = function(){
                me.initContainer({container : $dialog});
                complete();
            };

            //表单操作
            function formController(){
	            var $this = $(this),
		            $dialog = $this.hasClass('modal-dialoger') ? $this : $this.parents('.modal-dialoger'),
		            form;
                form = $dialog.find('form.required-validate');
                if(form.length > 0){
                    me.ajaxValidForm({
                        form : form.get(0),
                        complete : function(response){
                            if(response.status){
                                $dialog.modal('hide');
                            }
                        }
                    });
                }else{
                    $dialog.modal('hide');
                }
            }

            $dialog = dialoger.dialog(options);
        },

        //本页面弹出指定元素窗口
        popup : function(options){
            var me = this;
            options.okHandler = options.okHandler;
            dialoger.dialog(options);
        },

        //绑定图
        handlerMap : [
            //弹出窗口
            {
                frame : function(){
                    return cruder.dialog.apply(cruder, arguments);
                },
                load : function(){
                    return cruder.dialog.apply(cruder, arguments);
                },
                dialog : function(){
                    return cruder.dialog.apply(cruder, arguments);
                },
                popup : function(){
                    return cruder.dialog.apply(cruder, arguments);
                }
            },
            //一般ajax操作
            {
                request : function(){
                    return cruder.update.apply(cruder, arguments);
                }
            },
            //刷新
            {
                refresh : function(){
                    return cruder.refresh.apply(cruder, arguments);
                }
            },
            //搜索
            {
                search : function(){
                    return cruder.search.apply(cruder, arguments);
                }
            },
            //重置
            {
                reset : function(){
                    return cruder.reset.apply(cruder, arguments);
                }
            },
            //返回
            {
                back : function(){
                    return cruder.back.apply(cruder, arguments);
                }
            },
            //日期
            {
                datepicker : function(){
                    return cruder.datepick.apply(cruder, arguments);
                }
            },
            //排序
            {
                tableSort : function(){
                    return cruder.tableSort.apply(cruder, arguments);
                }
            },
            //菜单选择
            {
                tableSelect : function(){
                    return cruder.tableSelect.apply(cruder, arguments);
                }
            },
            //全选
            {
                checkAll : function(){
                    return cruder.checkAll.apply(cruder, arguments);
                }
            },
            //展开与折叠
            {
                expand : function(){
                    return cruder.expand.apply(cruder, arguments);
                },
                collapse : function(){
                    return cruder.collapse.apply(cruder, arguments);
                }
            }
        ],

        //操作邦定
        bindHandler : function(el, opts){
            var me = this, $el = $(el),
                options = tool.parseOptions(el);
            options = $.extend(options, opts);
            options.handler = el;
            //判断是否自动化
            if(options.automation === false || options.automation === 0){
                return;
            }
            //如果是工具栏中，则自动加上target
            if($el.parents('.toolbars').length > 0 && !options.noForm){
                options.target = options.target || this.target;
            }
            //确认操作
            if(options.confirm){
                this.confirm(function(){
                    execute();
                }, options);
            }else execute();

            //执行列表
            function execute(){
                var flag;
                //自定义操作
                if(typeof options.execute == 'function'){
                    flag = options.execute(options);
                }
                if(flag === false) return;
                //绑定遍历
                flag = false;
                $.each(me.handlerMap, function(i, item){
                    if(flag) return false;
                    $.each(item, function(m, node){
                        if(options[m] && node){
                            node.call(me, options);
                            flag = true;
                            return false;
                        }
                    });
                });
            }
        },

        //绑定图
        automationMap : [
            //树形表格
            {
                treeTable : function(options){
                    require(['treetable'], function(treetable) {
                        treetable.automation(options.handler, options);
                    });
                }
            },
            //基本表格
            {
                table : function(options){
                    require(['grider'], function(grider){
                        grider.tableAutomation(options.handler, options);
                    });
                }
            },
            //tabs
            {
                tabs : function(){
                    return cruder.tabs.apply(cruder, arguments);
                }
            },
            //编辑器
            {
                editor : function(){
                    return cruder.editor.apply(cruder, arguments);
                }
            },
            //上传
            {
                uploader : function(){
                    return cruder.uploader.apply(cruder, arguments);
                }
            },
            //剪切
            {
                croper : function(){
                    return cruder.croper.apply(cruder, arguments);
                }
            },
            //图片
            {
                imager : function(){
                    return cruder.imager.apply(cruder, arguments);
                }
            },

            //表单验证
            {
                validate : function(options){
                    cruder.validate(options);
                }
            }
        ],

        //自动化
        automation : function(el, opts){
            var me = this, $el = $(el),
                options = tool.parseOptions(el);
            options = $.extend(options, opts);
            options.el = options.handler = el;

            //判断是否自动化
            if(options.automation === false || options.automation === 0){
                return;
            }

            //绑定遍历
            var flag = false;
            $.each(me.automationMap, function(i, item){
                if(flag) return false;
                $.each(item, function(m, node){
                    if(options[m] && node){
                        node.call(me, options);
                        flag = true;
                        return false;
                    }
                });
            });
        },

        //全选
        checkAll : function(options){
            var $el = $(options.handler),
                $form = this.get$form(options),
                checkboxes = $form.find(options.checkbox || 'input[type=checkbox][value!=all]'),
                flag;
            if($el.prop("checked")){
                flag = false;
            }else flag = true;
            checkboxes.each(function(i){
                var $this = $(this);
                $(this).prop("checked", flag);
            });
        },

        //搜索
        search : function(options){
            var $handler = $(options.handler),
                $form = $handler.parents('form'),
                params = {};
            if($form.length > 0){
                params = tool.serializeObject($form);
                options.paramsSearch = params;
            }

            if(options.search == 'grid'){
                require(['grider'], function(grider){
                    grider.search(options);
                });
            }
            //基于bs表格选择模块搜索
            else if(options.cat == 'west' || options.cat == 'east'){
                require(['dataselector'], function(dataselector){
                    dataselector.search(options);
                });
            }
            //基于easyui表格选择模块搜索
            else if(options.target == 'westGrid' || options.target == 'eastGrid'){
                require(['gridselector'], function(gridselector){
                    gridselector.search(options);
                });
            }
        },

        //展开
        expand : function(options){
            if(options.expand == 'tree'){
                require(['tree'], function(tree){
                    tree.expand(options);
                });
            }else if(options.expand == 'treegrid'){
                require(['treegrider'], function(treegrider){
                    options.target = options.target || me.target;
                    treegrider.expand(options);
                });
            }
        },

        //折叠
        collapse : function(options){
            if(options.collapse == 'tree'){
                require(['tree'], function(tree){
                    tree.collapse(options);
                });
            }else if(options.collapse == 'treegrid'){
                require(['treegrider'], function(treegrider){
                    options.target = options.target || me.target;
                    treegrider.collapse(options);
                });
            }
        },

        //添加检测
        validate : function(options){
            require(['validater'], function(validater){
                validater.validate(options);
            });
        },

        //日期
        datepick : function(options){
            require(['dater'], function(dater){
                dater.picker(options);
            });
        },

        //排序
        tableSort : function(options){
            require(['grider'], function(grider){
                grider.tableSort(options);
            });
        },

        //菜单选择
        tableSelect : function(options){
            require(['grider'], function(grider){
                grider.tableSelect(options);
            });
        },

        //编辑器
        editor : function(options){
            require(['editor'], function(editor){
                editor.build(options);
            });
        },

        //tabs
        tabs : function(options){
            require(['tabs'], function(tabs){
                tabs.build(options);
            });
        },

        //上传
        uploader : function(options){
            require(['uploader'], function(uploader){
                uploader.build(options);
            });
        },

        //剪切
        croper : function(options){
            require(['croper'], function(croper){
                croper.build(options);
            });
        },

        //图片
        imager : function(options){
            
        },

        //初始化容器
        initContainer : function(opts){
            var options = $.extend({}, opts),
                $container = options.container ? $(options.container) : $(document);

            //data-options自动化
            $container.find('[data-options]').each(function(){
                cruder.automation(this);
            });

            //placeholder设置
            var $placeholders = $container.find('input[placeholder],textarea[placeholder]');
            if($placeholders.length > 0){
                require(['placeholder'], function(){
                    $placeholders.placeholder();
                });
            }

        },

        //获取所在表单
        get$form : function(options){
            var $el = $(options.handler),
                $parentForm = $el.parents('form'),
                $form = options.target ? $(options.target) : ($parentForm.length > 0) ? $parentForm : $(this.target);
            return $form;
        },

        //默认标题
        title : '温馨提示',

        //默认表格选选择器
        target : '.grid-form'

    };

    /****初始化设置****/
    //事件设置
    var $body = $('body');
    $body.on('mouseup', '[data-options]', function (e) {
        var $this = $(this), tagName = (this.tagName || '').toLowerCase();
        if(e.button == 2) return !1;
        //按钮设置
        if(this.type == 'button' || this.type == 'checkbox' || /^(button|a|th|td|img)$/.test(tagName)){
            cruder.bindHandler(this);
        }
    });

    $body.on('focus', '[data-options]', function (e) {
        var $this = $(this), tagName = (this.tagName || '').toLowerCase();
        //input文本框设置
        if(this.type == 'text' || tagName == 'textarea'){
            //树形表格
            if($this.parents('.treetable').length > 0){
                return;
            }
            else cruder.bindHandler(this);
        }
    });

    return cruder;
});